package cn.itcast.microservice.order.service;

import cn.itcast.microservice.order.feign.ItemFeignClient;
import cn.itcast.microservice.order.pojo.Item;
import cn.itcast.microservice.order.properties.OrderProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by User on 2018/2/25.
 */
@Service
public class ItemService {


    // Spring框架对RESTful方式的http请求做了封装，来简化操作
    @Autowired
    private RestTemplate restTemplate;

//    @Value("${itcast.item.url}")
//    private String itemUrl;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private OrderProperties orderProperties;

    @Autowired
    private ItemFeignClient itemFeignClient;

    /**
     * 采用feign声明式调用服务
     * @param id
     * @return
     */
    public Item queryItemById(Long id){
        return itemFeignClient.queryItemById(id);
    }

    /**
     * 开启了负载均衡，并进行容错处理
     * @param id
     * @return
     */
    /*@HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod")
    public Item queryItemById(Long id){
        String serviceId = "itcast-microservice-item";

        return this.restTemplate.getForObject("http://" + serviceId + "/item/" + id, Item.class);
    }*/

    public Item queryItemByIdFallbackMethod(Long id){ // 请求失败执行的方法
        return new Item(id, "查询商品信息出错!", null, null, null);
    }

    /**
     * 开启了负载均衡
     *
     * @param id
     * @return
     */
    /*public Item queryItemById(Long id){
        String serviceId = "itcast-microservice-item";

        return this.restTemplate.getForObject("http://" + serviceId + "/item/" + id, Item.class);
    }*/

    /**
     * 未开启负载均衡
     *
     * @param id
     * @return
     */
    /*public Item queryItemById(Long id) {

        String serviceId = "itcast-microservice-item";
        List<ServiceInstance> instances = this.discoveryClient.getInstances(serviceId);
        if (instances.isEmpty()){
            return null;
        }

        // 为了演示，在这里获取一个实例
        ServiceInstance serviceInstance = instances.get(0);
        String url = ((EurekaDiscoveryClient.EurekaServiceInstance) serviceInstance).getInstanceInfo().getIPAddr() + ":" + serviceInstance.getPort();


        return this.restTemplate.getForObject("http://" + url + "/item/" + id, Item.class);
    }*/
}
